import React, { useContext, useState } from 'react';
import { Empty, message, Select } from 'antd';
import EmployeeDetailContext from '@/pages/Organization/EmployeeManage/EmployeeDetail/store/context';
import { useDeepCompareEffect } from 'react-use';
import { parseEmployeeExtendInfoList } from '@/pages/Organization/EmployeeManage/components/EmployeeInfoSections/util';
import { useRequest, useDictionary, defaultFormatResult } from '@/hooks';
import { getEmployeeFieldConfig } from '@/pages/Organization/EmployeeManage/services';
import FormContainer, { FormItem } from './FormContainer';

/**
 * 员工档案 - 工资社保 - 个税专项扣除
 */
const CpfSection = ({ formData, readonly, saveAction, onChange }) => {
    const employeeDetailContext = useContext(EmployeeDetailContext);
    const currentEmployeeCountryCode = employeeDetailContext?.employeeInfo?.countryNameCode;

    const [cpfPayTypeList, getCpfPayListText] = useDictionary('cpfPayType');

    // 因为国际化的字段是在 employeeExtendInfoList 数组里面, 这里将它打散到 formData 里面
    const [parsedFormData, setParsedFormData] = useState();
    // 获取国际化字段的默认配置
    const { data: employeeFieldConfig } = useRequest(
        () => getEmployeeFieldConfig({ countryNameCode: currentEmployeeCountryCode, groupCode: 'CPF' }),
        {
            ready: !!currentEmployeeCountryCode,
            refreshDeps: [currentEmployeeCountryCode],
            ...defaultFormatResult
        }
    );

    // mounted
    useDeepCompareEffect(() => {
        const employeeExtendInfoMap = parseEmployeeExtendInfoList(
            formData?.employeeExtendInfoList ?? [],
            currentEmployeeCountryCode
        );
        const combineData = { ...formData, ...employeeExtendInfoMap };
        setParsedFormData(combineData);
    }, [formData]);

    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });

    // 保存
    const handleSubmit = async values => {
        // 扩展字段处理
        const employeeExtendInfoList = employeeFieldConfig.map(item => ({
            ...item,
            fieldValue: values[item.fieldCode]
        }));
        const submitData = Object.assign({
            ...formData,
            employeeExtendInfoList
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData);
        } else {
            message.error(res.msg);
        }
    };

    return (
        // render
        <FormContainer
            title="CPF信息"
            hasEditAuth={!readonly && !!saveAction && !!employeeFieldConfig}
            flexLayout
            onSubmit={handleSubmit}
        >
            {({ getFieldDecorator }) =>
                parsedFormData ? (
                    <>
                        <FormItem
                            label="CPF缴交类型"
                            show={currentEmployeeCountryCode === 'SG'}
                            normalComponent={() => (
                                <div className="multiLineText">{getCpfPayListText(parsedFormData.cpfPayType)}</div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('cpfPayType', {
                                    initialValue: parsedFormData?.cpfPayType || undefined,
                                    rules: [
                                        {
                                            required: true,
                                            message: 'CPF缴交类型不能为空'
                                        }
                                    ]
                                })(
                                    <Select placeholder="请选择CPF缴交类型">
                                        {cpfPayTypeList?.map(item => (
                                            <Select.Option value={item.value} key={item.value}>
                                                {item.text}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                )
                            }
                        />
                    </>
                ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )
            }
        </FormContainer>
    );
};

export default CpfSection;
